package com.example.Lezedata.net;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.example.Lezedata.dataManager.LoginManager;
import com.example.Lezedata.util.GBToast;
import com.google.gson.JsonObject;

import org.json.JSONException;
import org.json.JSONObject;

import common.Errorcode;
import io.grpc.stub.StreamObserver;


public class ServerResponseObserver<V> implements StreamObserver {

    public ServerResponseObserver() {}

    private Throwable throwable;
    private Object object;
    private GBError error;
    public interface requestListener<V>{
        void complete(V value,GBError error);
    }
    public interface requestCompleteListener{
        void complete();
    }

    public requestListener listener;

    public <V>ServerResponseObserver(requestListener listener){
        this.listener = listener;
    }

    public static <V>ServerResponseObserver observer(requestListener listener){
        return new ServerResponseObserver(listener);
    }

    @Override
    public void onNext(Object value) {
        object = value;
        callBack();
    }

    @Override
    public void onError(final Throwable t) {
        throwable = t;
        String string = t.getMessage();
        if (string.startsWith("UNIMPLEMENTED")){
            int start = string.indexOf("{");
            int end = string.indexOf("}");
            string = string.substring(start,end + 1);
        }
        try {
            JSONObject object = new JSONObject(string);
            if (object != null){
                error = GBError.newInstance(object.getString("code"),object.getString("desc"));
                Log.d("GBError",String.format("请求错误描述=====>: code %s desc %s",error.code,error.desc));
            }
        } catch (JSONException e) {
            String obj = String.format("服务器返回的json错误=====>:%s",string);
            Log.d("GBError",obj);
            error = GBError.newInstance("-10000",obj);
//            e.printStackTrace();
        }
        callBack();
    }

    @Override
    public void onCompleted() {
        Log.d("TAG", "onCompleted: ");
    }

    private void callBack(){
        if (listener != null){
            Handler mainHandler = new Handler(Looper.getMainLooper());
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (error != null){
                        GBToast.showErrorToast(error.desc);
                    }
                    /// token 过期统一处理
                    if (error.isEqTipCode(Errorcode.TipCode.Code100006)){
                        LoginManager.instance().exitLogin();
                    }
                    listener.complete(object,error);
                }
            });
        }
    }
}
